package common

import (
	"fmt"
	"go-toy/util"
	"os"
)

type File struct {
}

// Return the name of the log file.
func (f *File) Name() string {
	logDrive := util.Viper.GetString("log.drive")
	return fmt.Sprintf("%s.log", logDrive)
}

// Return the path of the log file.
func (f *File) Path() string {
	// day := time.Now().Day()
	// month := time.Now().Month()
	// year := time.Now().Year()

	logDrive := util.Viper.GetString("log.drive")
	logFilePath := util.Viper.GetString(fmt.Sprintf("log.%s.path", logDrive))
	if logFilePath == "" {
		logFilePath = "./log"
	}

	return logFilePath
	// return fmt.Sprintf("%s/%d/%02d/%02d", logFilePath, year, month, day)
}

// Create the directory of the log file if it does not exist.
func (f *File) CreatedPath() {
	logFilePath := f.Path()

	if _, err := os.Stat(logFilePath); os.IsNotExist(err) {
		err := os.MkdirAll(logFilePath, 0777)
		if err != nil {
			panic("Failed to create log directory.")
		}
	}
}

// Return the full path and name of the log file.
func (f *File) PathName() string {
	return fmt.Sprintf("%s/%s", f.Path(), f.Name())
}

// Create the log file if it does not exist.
func (f *File) CreatedFile() *os.File {
	pathname := f.PathName()

	f.CreatedPath()

	file, err := os.OpenFile(pathname, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		panic("Failed to create log file.")
	}
	return file
}

var FileIntance = &File{}
